package com.easywan.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.imageio.ImageIO;

import org.springframework.util.SystemPropertyUtils;

import com.easywan.core.Config;


public class ImageUtils {
	/**
	 * 将图片写到file中
	 * @param img
	 * @param file
	 * @throws IOException
	 */
	public static void wirte(BufferedImage img,File file) throws IOException{
		String fileUri = file.getPath();
		File fileUriPath = new File(fileUri);
		if(!fileUriPath.exists()){
			fileUriPath.mkdirs();
		}
		
		 ImageIO.write(img, "PNG", file);
	}
	private static BufferedImage drawImg(InputStream is) throws IOException{
		BufferedImage bi = ImageIO.read(is);
		return bi;
	}
	private static BufferedImage drawImg(File is) throws IOException{
		BufferedImage bi = ImageIO.read(is);
		return bi;
	}
	public static Boolean scala(InputStream f,int width,File to) throws IOException{
		 BufferedImage bi = ImageIO.read(f);
		 if(width < bi.getWidth()){
			 double ratio = width * 1.0 / bi.getWidth();
			 Image itemp = null;//bi.getScaledInstance(width, (int)(bi.getHeight() * ratio), bi.SCALE_SMOOTH);
			 AffineTransformOp op = new AffineTransformOp(AffineTransform
                     .getScaleInstance(ratio, ratio), null);
             itemp = op.filter(bi, null);
             wirte((BufferedImage) itemp,to);
		 }else{
			 wirte(bi,to);
		 }
		 return true;
	}
	public static BufferedImage scala(BufferedImage bi,int width) throws IOException{
		System.out.println(bi.getHeight() * (width/(bi.getWidth()*1.0)));
		BufferedImage tmp = new BufferedImage(width, (int) (bi.getHeight() * (width*1.0/bi.getWidth())), BufferedImage.TYPE_INT_RGB);
		   Graphics2D g2 = tmp.createGraphics();
		   g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
		   g2.drawImage(bi, 0, 0, width, (int)(bi.getHeight() * (width*1.0/(bi.getWidth()))), null);
		   g2.dispose();
		   
		   return tmp;
	}
	public static Boolean save(String imageUrls, String string,int w) throws  IOException {
		try{ 
		URL url = new URL(imageUrls);    
	     HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
	                //设置超时间为3秒  
        conn.setConnectTimeout(3*1000);  
        //防止屏蔽程序抓取而返回403错误  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
        //得到输入流  
	     InputStream inputStream = conn.getInputStream();    
		File image = new File(string);
		if(!image.exists()){
			image.mkdirs();
		}
		//System.out.println(image.getAbsolutePath());
		return scala(inputStream,w,image);
		
		}catch(FileNotFoundException e){
			return false;
		}
		
	}
	
	/**
	 * 获取Image
	 * @param path 对应路径
	 * @param api 如果本地没有，则远程调用
	 * @return
	 * @throws IOException 
	 */
	
	public static BufferedImage getImage(String path,String api) throws IOException{
		System.out.println("开始加载图片------------------------------");
		System.out.println("图片参数:"+path);
		System.out.println("图片API:"+api);
		if(path == null || path == "") return null;
		String resourcePath = Config.get("resourcePath");
		File savePath = new File( resourcePath+"/" + path);
		
		BufferedImage iio = null;
		if(savePath.exists()){
			System.out.println("图片已经存在:"+savePath);
			iio = ImageIO.read(savePath);
		}else
		{
			try{
			iio = ImageIO.read(getRemoteInputStream(api));
			System.out.println("图片不存在：调用API："+api);
			wirte(iio,savePath);
			}catch(Exception e){
				return null;
			}
		}
		System.out.println("结束加载图片------------------------------");
		return iio;
	}
	public static InputStream getRemoteInputStream(String imageUrls) throws IOException{
		URL url = new URL(imageUrls);    
	     HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
	                //设置超时间为3秒  
       conn.setConnectTimeout(3*1000);  
       //防止屏蔽程序抓取而返回403错误  
       conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
       //得到输入流  
	     InputStream inputStream = conn.getInputStream();  
	     return inputStream;
	}
	/**
	 * 
	 * @param saImage
	 * @param bgImage
	 * @return
	 */
	public static BufferedImage addImage(BufferedImage saImage, BufferedImage bgImage) {
		return addImage(saImage, bgImage,0,0);
	}
	/**
	 * 从 xx处开始
	 * @param image
	 * @param bgImage
	 * @param i
	 * @param j
	 * @return
	 */
	public static BufferedImage addImage(BufferedImage image, BufferedImage bgImage, int left, int top) {
		if(image == null || bgImage == null ){
			if(image == null){ return bgImage; }
			if(bgImage == null){ return bgImage;}
		}
		//image
		BufferedImage result = image;//new BufferedImage(image.getWidth(), bgImage.getWidth(), BufferedImage.TYPE_3BYTE_BGR);
		
		Graphics2D gd = result.createGraphics(); 
		//gd.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0f));
		gd.drawImage(bgImage, left, top, bgImage.getWidth(), bgImage.getHeight(),null );
		gd.dispose();
		/*System.out.println("height:"+bgImage.getHeight());
		System.out.println("width:"+bgImage.getWidth());
		System.out.println("result.height:"+result.getHeight());
		System.out.println("result.width:"+result.getWidth());*/
		
		/*for(int i = 0; i+left < bgImage.getWidth(); i ++){
			int flags = 0;
			for(int j = 0; j+top <bgImage.getHeight(); j++){
				//System.out.println(bgImage.getRGB(i, j));
				int rgb = bgImage.getRGB(i, j);
				if(rgb < 0 ){
					if(flags >= 1){
						result.setRGB(i+left, j+top,rgb);
					}else{
						flags++;
					}
					//System.out.println(bgImage.getRGB(i, j));
				}
			}
		}*/
		return result;
	}
	public static BufferedImage drawImg(BufferedImage bi, String string, Font font,Color c,int height) {
		
		Graphics g = bi.getGraphics();
		Graphics2D g2d = bi.createGraphics();
		FontMetrics fm = g2d.getFontMetrics(font);
        int textWidth = fm.stringWidth(string);
        int widthX = (bi.getWidth() - textWidth) / 2;
		g.setFont(font);
		g.setColor(c);
		g.drawString(string, widthX, height);
		g.dispose();  
		return bi;
	}
	public static BufferedImage addImageBack(BufferedImage bi, BufferedImage picture, int i, int j) {
		BufferedImage image = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_BGR);
		Graphics2D g2d = image.createGraphics();
		g2d.setColor(Color.white);
		g2d.fillRect(0, 0, bi.getWidth(), bi.getHeight());
		g2d.dispose();
		//System.out.println("picture:"+picture.getWidth());
		image = addImage(image, picture,i,j);
		image = addImage(image,bi);
		return image;
	}
	/*public static BufferedImage delete(BufferedImage picture, BufferedImage bg, int i, int j) {
		
		return null;
	}*/
}
